const WebSocket = require("ws");
const url = require("url");
const WebSocketServer = WebSocket.Server;
const wss = new WebSocketServer({port: 3001,});

// 生成唯一ID
function createId() {
  let e = () =>
    Math.floor((1 + Math.random()) * 65536)
      .toString(16)
      .substring(1);
  return `${e()}${e()}-${e()}-${e()}-${e()}-${e()}${e()}`;
}

//  存储连接的客户端
const people = {};
wss.on("connection", function (ws, req) {
  const connectionParams = url.parse(req.url, true).query;
  const sessionId = connectionParams.sessionId || createId();
  console.log('接受客户端连接', sessionId)
  people[sessionId] = {
    sessionId,
    ws,
  };

  ws.on("message", function (message) {
    message = message.toString();
    message = JSON.parse(message);
    let sId;
    switch (message.type) {
      case "connect":
        // 将连接的客户端存储起来
        ws.send(
          JSON.stringify({
            type: "connect",
            data: sessionId,
          })
        );
        break;
      case "call":
        // 将 sdp 发给接收端，sessionId 为 接收端的 id
        const sdp = message.data.sdp;
        sId = message.data.sessionId;
        if (people[sId]) {
          console.log('将 sdp 发给接收端，sessionId 为 接收端的 id', sId)
          people[sId].ws.send(
            JSON.stringify({
              type: "call",
              data: sdp,
            })
          );
        }
        break;
      case "answer":
        // 接收端将 sdp 发给发起端，sessionId 为 发起端的 id
        const answerSDP = message.data.sdp;
        sId = message.data.sessionId;
        if (people[sId]) {
          people[sId].ws.send(
            JSON.stringify({
              type: "answer",
              data: answerSDP,
            })
          );
        }
        break;
      case "ice":
        // 同步补充描述信息给目的端（通过SDP协商结果进行信息交换），描述信息包括协议、IP、端口、优先级等等信息
        sId = message.data.sessionId;
        if (people[sId]) {
          people[sId].ws.send(
            JSON.stringify(message)
          );
        }
        break;
      case "getAllClients":
        ws.send(
          JSON.stringify({
            type: "getAllClients",
            data: Object.keys(people),
          })
        );
        break;
    }
  });
  ws.on('close', e => {
    console.log('关闭', sessionId)
    delete people[sessionId]
  })
});

process.on('uncaughtException', e => {
  console.error(e)
})
process.on('unhandledRejection', e => {
  console.error(e)
})